<template>
  <div class="data-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-section">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item
          v-for="(item, index) in breadcrumbRoutes"
          :key="index"
          :to="{ path: item.path }"
        >
          {{ item.name }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 左右布局 -->
    <div class="layout-container">
      <!-- 左侧树形结构 -->
      <div class="left-panel">
        <TreeComponent :key="`tree-${currentPageType}`" @node-click="handleNodeClick" />
      </div>

      <!-- 右侧内容 -->
      <div class="right-panel">
        <!-- 上部筛选组件 -->
        <div class="filter-section">
          <FilterComponent
            :key="`filter-${currentPageType}-${isFirstNavigationFromCollection ? 'keep' : 'reset'}`"
            @change="handleFilterChange"
          />
        </div>

        <!-- 下部数据列表 -->
        <div class="list-section">
          <DataListComponent
            :pageType="currentPageType"
            :menuId="currentMenuId"
            :filterParams="filterParams"
            :key="`list-${currentPageType}-${currentMenuId}-${JSON.stringify(filterParams)}`"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
// 导入三个组件
import TreeComponent from './components/TreeComponent.vue'
import FilterComponent from './components/FilterComponent.vue'
import DataListComponent from './components/DataListComponent.vue'
import { useSearchStore } from '@/store/modules/search'

const route = useRoute()
const router = useRouter()
const searchStore = useSearchStore()

// 头部导航
const headerList: any = ref([
  { name: '首页', path: '/', id: '1' },
  { name: '数据目录', path: '/dataCatalog', id: '2' },
  { name: '数据集', path: '/dataset', id: '3' },
  { name: '数据接口', path: '/dataInterface', id: '4' },
  { name: '用户中心', path: '/userCenter', id: '5' }
])

// 首次从收藏页面导航过来的标记
const isFirstNavigationFromCollection = ref(false)

// 计算属性：根据路由参数生成面包屑
const breadcrumbRoutes = computed(() => {
  const routes: any = []

  // 首页是固定的
  routes.push({
    name: '首页',
    path: '/index'
  })

  // 根据路由参数path（对应headerList的path）来添加相应的面包屑
  const currentType = route.path

  if (currentType) {
    const currentItem = headerList.value.find((item) => item.path == currentType)
    if (currentItem) {
      routes.push({
        name: currentItem.name,
        path: currentItem.path
      })
    }
  }

  return routes
})

// 计算当前页面类型
const currentPageType = computed<'directory' | 'interface' | 'dataset'>(() => {
  const path = route.path

  if (path === '/dataCatalog') {
    return 'directory'
  } else if (path === '/dataInterface') {
    return 'interface'
  } else if (path === '/dataset') {
    return 'dataset'
  } else {
    // 默认返回数据目录类型
    return 'directory'
  }
})

// 当前选中的menuId
const currentMenuId = ref<any>(null)

// 筛选参数
const filterParams = reactive<Record<string, string>>({})

// 处理树节点点击事件
const handleNodeClick = (menuId: any) => {
  currentMenuId.value = menuId
}

// 处理筛选条件变化
const handleFilterChange = (params: Record<string, string>) => {
  // 清空现有筛选参数
  Object.keys(filterParams).forEach((key) => {
    delete filterParams[key]
  })

  // 设置新的筛选参数
  Object.assign(filterParams, params)
}

// 处理搜索
const handleSearch = () => {
  // 触发数据重新加载
  if (currentPageType.value === 'directory') {
    // 这里可以通过重新渲染DataListComponent来触发数据加载
    // 由于我们使用了watch监听，修改key可以强制重新渲染
  }
}

// 监听路由变化
const handleRouteChange = (to: any, from: any) => {
  // 检查是否从MyCollections页面跳转过来
  const isFromCollection = from.path === '/userCenter'
  // 新增：检查是否从首页搜索跳转过来
  const isFromIndexSearch = from.path === '/index'
  const isToDataPage = ['/dataCatalog', '/dataset', '/dataInterface'].includes(to.path)

  // 如果是从收藏页面首次跳转过来，保持筛选条件
  if ((isFromCollection || isFromIndexSearch) && isToDataPage) {
    isFirstNavigationFromCollection.value = true
  } else if (isToDataPage && !isFromCollection && !isFromIndexSearch) {
    // 从其他页面跳转过来，重置筛选条件
    isFirstNavigationFromCollection.value = false
    // 清空筛选参数
    Object.keys(filterParams).forEach((key) => {
      delete filterParams[key]
    })
    // 清空搜索框值
    searchStore.clearKeyword()
  }
}

onMounted(() => {
  // 注册路由变化监听
  router.afterEach(handleRouteChange)
})

onUnmounted(() => {
  // 移除路由变化监听
  router.afterEach(handleRouteChange)
})
</script>

<style scoped>
.data-container {
  width: 100%;
  /* height: 100%; */
  padding: 16px;
  background: #eff4fa;
}

.breadcrumb-section {
  margin-bottom: 16px;
  padding: 12px 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.layout-container {
  display: flex;
  /* height: calc(100vh - 100px); */
  gap: 16px;
}

.left-panel {
  width: 400px;
  min-width: 250px;
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-section {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.list-section {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: auto;
}
</style>
